import cherrypy
import mimetypes
import csv, time, os
mimetypes.types_map['.css'] = 'text/css'

class web(object):
	def index(self):
		t = open('template/threads.txt','r').read()
		pt = open('template/threadlist.txt','r').read()
		arts = [x.replace('.csv','') for x in os.listdir('.') if '.csv' in x]
		p = ''
		for art in arts:
			p+= pt.format(art,art)
		t = t.format(p)
		return t
	def re(self, input='None'):
		return input
	def text_html(self,input=None):
		return '404 Error!\n<br>\n'+str(input)
	def thread(self,art='general'):
		t = open('template/thread.txt','r').read()
		pt = open('template/post.txt','r').read()
		#content = ('1','Jack','Thursday','Hello how is everyone?')
		p = ''
		with open('threads/'+art+'.csv','rb') as f:
			reader = csv.reader(f,delimiter=',',
				quotechar='"',quoting=csv.QUOTE_ALL)
			for row in reader:
				p += pt.format(*row)
		t = t.format(p,art)
		return t
	def newpost(self,user,msg,art='general'):
		date = time.strftime('%b_%d %H:%M')
		i = []
		with open('threads/'+art+'.csv','rb') as f:
			reader = csv.reader(f,delimiter=',',
				quotechar='"',quoting=csv.QUOTE_ALL)
			for row in reader:
				i.append(row)
		num = (len(i)+1)
		with open('threads/'+art+'.csv','ab+') as f:
			writer = csv.writer(f,delimiter=',',
				quotechar='"',quoting=csv.QUOTE_ALL)
			writer.writerow([num,user,date,msg])
		raise cherrypy._cperror.InternalRedirect('thread')
	def newthread(self,art,user,msg):
		art = art.replace(' ','_')
		if os.path.isfile('threads/'+art+'.csv'):
			return 'Thread alread exists'
		f = open('threads/'+art+'.csv','w+')
		f.close()
		q = newpost(user,msg,art)
		return q
	newpost.exposed = True
	index.exposed = True
	re.exposed = True
	thread.exposed = True

cherrypy.quickstart(web(),'/','server.conf')

# Forum